<?php
declare (strict_types = 1);

namespace app\controller;

use app\service\GoodsService;
use app\service\HouseService;
use app\service\OrderService;
use app\service\ShowService;
use think\facade\Db;
use think\Request;
use app\common\BaseController;


class HouseController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $product = $request->param('product', '');
      $model = $request->param('model', '');
      $conditions = [];
      if ($product) {
        $conditions[] = ['product', $product, '='];
      }
      if ($model) {
        $conditions[] = ['model', $model, '='];
      }
      $order = ['product' => 'desc', 'productn' => 'desc', 'id' => 'desc'];
      $list = HouseService::getInstance()->getHouseList($conditions,$page,$pageSize,$order);
      // 获取展厅列表
      $res = Db::table('show_t')
        ->field('product,model,productn,SUM(amoumt)as total')
        ->where('states', '=', 1)
        ->group('product,model,productn')
        ->select()
        ->toArray();
      $showList = [];
      foreach ($res as $value) {
        $str = $value['productn'].'-'.$value['model'];
        $showList[$str] = $value['total'];
      }
      foreach ($list as &$v) {
        $str = $v['productn'].'-'.$v['model'];
        $v['nowamoumt'] = $v['amoumt'] + $v['wamoumt'] + $v['badamoumt'] + $v['oldamoumt'] + $v['oldwamoumt'];
        $v['show'] = isset($showList[$str]) ? $showList[$str]*1 : 0;
      }
      $pager = HouseService::getInstance()->getHousePager($conditions,$page,$pageSize);
      return $this->send200ResponseWithPager($list, $pager);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $data = HouseService::getModel()->find($id);
        return $this->send200Response($data);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
      $data = $request->param('data', []);
      $res = HouseService::getInstance()->updateHouse($id, $data);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        return $id;
    }

    /**
     * 通过类型获取库存详情
     *
     * @return \think\Response
     */
    public function getHouseByProduct(Request $request)
    {
      $product = $request->param('product', '');
      $list = Db::name("House")
        ->where('product', '=', $product)
        ->select()
        ->toArray();
      $result = [
        'houseList' => array_unique(array_column($list, 'productn')),
        'modelList' => []
      ];
      foreach ($list as $value) {
        $result['modelList'][$value['productn']][$value['id']] = $value;
      }
      return $this->send200Response($result);
    }

    /**
     * 获取入库明细
     */
    public function getHouseIn(Request $request) {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $start_date = $request->param('start_date', '');
      $end_date = $request->param('end_date', '');
      $purCond = [
        ['inhouse', 1, '=']
      ];
      if ($start_date) {
        $purCond[] = ['date', $start_date, '>='];
      }
      if ($end_date) {
        $purCond[] = ['date', $end_date, '<='];
      }
      $data = [];
      // 获取采购列表
      $purchase = GoodsService::getInstance()->getGoodsByCondition($purCond);
      foreach ($purchase as $pValue) {
        $data[] = [
          'date' => $pValue['date'],
          'type' => 1,
          'product' => $pValue['product'],
          'productn' => $pValue['productn'],
          'model' => $pValue['model'],
          'amoumt' => $pValue['amoumt'],
          'unit' => $pValue['unit'],
          'cost' => $pValue['price'],
          'total' => $pValue['total'],
          'intime' => $pValue['installtime'],
          'datesort' => strtotime($pValue['date'])
        ];
      }
      // 获取返仓列表
      $showCon = [
        ['states', 0, '=']
      ];
      if ($start_date) {
        $showCon[] = ['date', $start_date, '>='];
      }
      if ($end_date) {
        $showCon[] = ['date', $end_date, '<='];
      }
      $reShow = ShowService::getInstance()->getAllShow($showCon, ['backtime' => 'desc', 'id' => 'desc']);
      foreach ($reShow as $sValue) {
        $data[] = [
          'date' => $sValue['date'],
          'type' => 2,
          'product' => $sValue['product'],
          'productn' => $sValue['productn'],
          'model' => $sValue['model'],
          'amoumt' => $sValue['amoumt'],
          'unit' => $sValue['unit'],
          'cost' => $sValue['cost'],
          'total' => round($sValue['cost'] * $sValue['amoumt'], 2),
          'intime' => $sValue['backtime'],
          'datesort' => strtotime($sValue['date'])
        ];
      }
      // 排序
      foreach ($data as $key=>$value){
        $dateSort[$key] = $value['datesort'];
        $typeSort[$key] = $value['type'];
      }
      if ($data) {
        array_multisort($dateSort,SORT_NUMERIC,SORT_DESC, $typeSort,SORT_NUMERIC,SORT_ASC, $data);
      }

      // 分页
      $count = count($data); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];

      $list = array_slice($data, $start, intval($pageSize));
      return $this->send200ResponseWithPager($list,$pager);

    }

    /**
     * 获取出库明细
     */
    public function getHouseOut(Request $request) {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $start_date = $request->param('start_date', '');
      $end_date = $request->param('end_date', '');
      $orderCond = [
        ['send', 1, '=']
      ];
      if ($start_date) {
        $orderCond[] = ['date', $start_date, '>='];
      }
      if ($end_date) {
        $orderCond[] = ['date', $end_date, '<='];
      }
      $data = [];
      // 获取订单列表
      $order = OrderService::getInstance()->getAllOrder($orderCond, ['date' => 'desc', 'id' => 'desc']);
      foreach ($order as $oValue) {
        $data[] = [
          'date' => $oValue['date'],
          'type' => 1,
          'product' => $oValue['product'],
          'productn' => $oValue['productn'],
          'model' => $oValue['model'],
          'amoumt' => $oValue['amoumt'],
          'unit' => $oValue['unit'],
          'cost' => $oValue['cost'],
          'price' => $oValue['price'],
          'total' => round($oValue['cost'] * $oValue['amoumt'], 2),
          'tprice' => $oValue['tprice'],
          'outtime' => $oValue['sendtime'],
          'datesort' => strtotime($oValue['date'])
        ];
      }
      // 获取展厅列表
      $showCon = [
        ['states', [0,1,2], 'IN']
      ];
      if ($start_date) {
        $showCon[] = ['date', $start_date, '>='];
      }
      if ($end_date) {
        $showCon[] = ['date', $end_date, '<='];
      }
      $ShowList = ShowService::getInstance()->getAllShow($showCon, ['date' => 'desc', 'id' => 'desc']);
      foreach ($ShowList as $sValue) {
        $data[] = [
          'date' => $sValue['date'],
          'type' => 2,
          'product' => $sValue['product'],
          'productn' => $sValue['productn'],
          'model' => $sValue['model'],
          'amoumt' => $sValue['amoumt'],
          'unit' => $sValue['unit'],
          'cost' => $sValue['cost'],
          'price' => '',
          'total' => round($sValue['cost'] * $sValue['amoumt'], 2),
          'tprice' => '',
          'outtime' => $sValue['date'],
          'datesort' => strtotime($sValue['date'])
        ];
      }
      // 排序
      $dateSort = [];
      $typeSort = [];
      foreach ($data as $key=>$value){
        $dateSort[$key] = $value['datesort'];
        $typeSort[$key] = $value['type'];
      }
      if ($dateSort && $data && $typeSort) {
        array_multisort($dateSort,SORT_NUMERIC,SORT_DESC, $typeSort,SORT_NUMERIC,SORT_ASC, $data);
      }

      // 分页
      $count = count($data); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];

      $list = array_slice($data, $start, intval($pageSize));
      return $this->send200ResponseWithPager($list,$pager);

    }
}
